functions-scopes
JavaScript Scope#
What is Scope?#
Scope determines the visibility or accessibility of a variable or other resource in the area of your code. Scope refers to what the execution context of a particular piece of code is. One of the most important things this context determines is what variables are available to that piece of code.
In ES5 JavaScript, scope is exclusively delimited by functions. In ES6 JavaScript, block-scoping has been introduced via the let and const keywords. Both these things will be explained further on.
Global Scope#
There's only one global scope in the JavaScript document. The area outside all the functions is consider the global scope and the variables defined inside the global scope can be accessed and altered in any other scopes.
Local Scope#
Variables that are usable only in a specific part of your code are considered to be in a local scope. These variables are also called local variables.
In JavaScript, there are two kinds of local scope: function scope and block scope.
Function Scope#
When you declare a variable in a function, you can access this variable only within that function. You can’t get this variable once you get out of it.
Block Scope#
A block scope is the area within if statement, switch conditions or for and while loops. Generally speaking, whenever you see {curly brackets}, it is a block. Block scoping was introduced to JavaScript via the let and const keywords, which are used to declare variables in the same way as var. The difference (in terms of scoping at least) is that while variables declared with var are available within the function in which they're defined, variables defined with let and const are only available within the block they're defined in:
So, lets add one more difference between var, let and const:
- Variables declared with
varare function-scoped. - Variables declared with
letorconstare block-scoped.
Lexical Scope#
Another point to mention is the lexical scope. Lexical scope means the children scope has the access to the variables defined in the parent scope.
Nested Scopes#
Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside its scope and inside its parent scope.
More formally, each function has access to its own local scope, and also the scope of the function that encloses it (or global scope, if there is no enclosing function).